package studio.xiaoyun.core.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import studio.xiaoyun.core.constant.SystemRole;
import studio.xiaoyun.core.dao.IPermissionDao;
import studio.xiaoyun.core.dao.IRoleDao;
import studio.xiaoyun.core.entity.PermissionEntity;
import studio.xiaoyun.core.entity.RoleEntity;
import studio.xiaoyun.core.exception.InvalidParameterException;
import studio.xiaoyun.core.parameter.PermissionParameter;
import studio.xiaoyun.core.parameter.RoleParameter;
import studio.xiaoyun.core.parameter.criterion.Query;
import studio.xiaoyun.core.service.IRoleService;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色相关
 */
@Service
public class RoleService implements IRoleService{
    private Logger logger = LoggerFactory.getLogger(RoleService.class);
    @Resource
    private IRoleDao roleDao;
    @Resource
    private IPermissionDao permissionDao;

    @Override
    public void setRolePermission(String roleId, List<String> permissionIds) {
        logger.debug("修改角色的权限，角色id:{}",roleId);
        RoleEntity role = roleDao.getById(roleId);
        Set<PermissionEntity> permissionSet;
        if(permissionIds==null || permissionIds.isEmpty()){
            permissionSet = Collections.emptySet();
        }else{
            PermissionParameter params = new PermissionParameter();
            params.addQuery(Query.in("permissionId",permissionIds));
            List<PermissionEntity> permissionList = permissionDao.getPermissionsByParameter(params);
            if(permissionIds.size()!=permissionList.size()){
                throw new InvalidParameterException("权限id不存在");
            }
            permissionSet = permissionList.stream().collect(Collectors.toSet());
        }
        role.setPermissions(permissionSet);
        roleDao.update(role);
    }

    @Override
    public void deleteRole(List<String> roleId) {
        logger.debug("删除角色，角色id:{}",roleId.toString());
        for(SystemRole systemRole:SystemRole.values()){
            if(roleId.contains(systemRole.getRoleId())){
                throw new InvalidParameterException("系统角色不能删除");
            }
        }
        for(String id:roleId){
            RoleEntity role = roleDao.getById(id);
            roleDao.delete(role);
        }
    }

    @Override
    public void updateRole(RoleEntity role){
        logger.debug("更新角色信息，角色id:{}，名称:{},描述:{}",role.getRoleId(),role.getName(),role.getDescription());
        if(StringUtils.isBlank(role.getRoleId())){
            throw new InvalidParameterException("角色id不能为空");
        }
        if(StringUtils.isBlank(role.getName())){
            throw new InvalidParameterException("角色名称不能为空");
        }
        for(SystemRole systemRole:SystemRole.values()){
            if(systemRole.getRoleId().equals(role.getRoleId()) && !systemRole.getName().equals(role.getName())){
                throw new InvalidParameterException("系统角色的名称不能修改");
            }
        }
        RoleEntity roleEntity = roleDao.getById(role.getRoleId());
        if(!roleEntity.getName().equals(role.getName())){  //如果修改角色名称，则判断名称是否已经存在
            RoleParameter param = new RoleParameter();
            param.setName(role.getName());
            long count = roleDao.getRoleCountByParameter(param);
            if(count>0){
                throw new InvalidParameterException("角色名称已经存在");
            }
        }
        roleEntity.setName(role.getName());
        roleEntity.setDescription(role.getDescription());
        roleDao.update(roleEntity);
    }

    @Override
    public String createRole(String name, String description) {
        logger.debug("创建角色，名称:{},描述:{}",name,description);
        if(StringUtils.isBlank(name)){
            throw new InvalidParameterException("角色名称不能为空");
        }
        RoleParameter param = new RoleParameter();
        param.setName(name);
        long count = roleDao.getRoleCountByParameter(param);
        if(count>0){
            throw new InvalidParameterException("角色名称已经存在");
        }
        RoleEntity role = new RoleEntity();
        role.setName(name);
        role.setDescription(description);
        return roleDao.save(role);
    }

}
